<template>
	<div class="table-custom">
		<el-table ref="tableRef" :height="tableHeight" v-loading="state.dataListLoading" :data="setDataList" border style="width: 100%">
			<template v-for="item,i in tableProp" :key="i">
				<el-table-column :prop="item.prop" :label="item.label" header-align="center" align="center" :width="item.width" :show-overflow-tooltip="item.tooltip">
					<template #default="scope">
						<!-- 特殊处理方式1、数据字段合并显示 -->
						<div v-if="specialType == 1 && item.specialType" class="flex flex-warp">
							<div class="w33 textL" v-for="ttem,t in scope.row[item.prop]" :key="t">{{ttem.label}}：{{ttem.value}}</div>
						</div>
						<!-- 1是2否的类型 -->
						<div v-else-if="item.radio">{{setRadioData(item.radioData,scope.row[item.prop])}}</div>
						<!-- 多列显示字段，比如三排部门名称 -->
						<div v-else-if="item.more">
							<div class="textL" v-for="tm,t in item.moreData" :key="t">{{scope.row[tm]}}</div>
						</div>
						<!-- 显示数据是对象类型的，需要obj.xxx -->
						<div v-else-if="item.obj">
							<div v-if="scope.row[item.prop]">{{scope.row[item.prop][item.objName]}}</div>
						</div>
						<!-- 显示数据是字符串对象类型的，需要obj.xxx -->
						<div v-else-if="item.strobj">
							<div v-if="scope.row[item.prop]">{{setCustomColumn(scope.row[item.prop],item.strvalue)}}</div>
						</div>
						<!-- 显示数据是数组类型的，需要显示数组内的obj.xxx -->
						<div v-else-if="item.array">
							<div class="textL" v-for="tm,t in scope.row[item.prop]" :key="t">{{tm[item.arrayName]}}</div>
						</div>
						<!-- 字段是单个图片地址类型 -->
						<div v-else-if="item.img">
							<div class="w100" v-if="scope.row[item.prop]" @click="preimg(scope.row[item.prop])">
								<img :src="scope.row[item.prop]" class="pointer" style="width:50px;height:50px;">
							</div>
						</div>
						<!-- 字段是多个图片地址类型（,号拼接） -->
						<div v-else-if="item.imgs">
							<el-button type="primary" v-if="scope.row[item.prop]" link @click="preimgs(scope.row[item.prop])">点击查看图片</el-button>
							<span v-else class="c999"></span>
						</div>
						<!-- 序号显示下标-->
						<div v-else-if="item.showIndex">
							<span class="c999">{{scope.$index+1}}</span>
						</div>
						<!-- 序号显示下标-->
						<div v-else-if="item.comp == 'account_type'">
							<div>
                                <div v-if="scope.row[item.prop] == 'free'">{{ $t('membership.Free') }}</div>
                                <div v-if="scope.row[item.prop] == 'basic'">{{ $t('membership.Basic') }}</div>
                                <div v-if="scope.row[item.prop] == 'company'">{{ $t('membership.Company') }}</div>
                                <div v-if="scope.row[item.prop] == 'sub'">{{ $t('membership.Sub') }}</div>
                                <div v-else></div>
                            </div>
						</div>
						<!-- 滑块操作-->
						<div v-else-if="item.optionSwitch">
							<el-switch
								v-model="scope.row[item.prop]"
								inline-prompt
								active-text="是"
								inactive-text="否"
								:active-value="item.optionSwitchOn"
								:inactive-value="item.optionSwitchOff"
								@change="handleSwitch(scope.row.id,$event)"
							/>
						</div>
						<!-- 默认字段 -->
						<div v-else>{{ getPropertyByPath(scope.row, item.prop) }}</div>
					</template>
				</el-table-column>
			</template>
			<el-table-column v-if="option.length > 0" label="操作" fixed="right" header-align="center" align="center" :width="optionWidth">
				<template #default="scope">
					<template v-for="item,i in option" :key="i">
						<el-button type="default" @click="handleClick(scope.row,item.value)" v-if="hasRule('pageRole/index/edit')">{{item.label}}</el-button>
					</template>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			v-if="showPage"
			:current-page="state.page"
			:page-sizes="state.pageSizes"
			:page-size="state.limit"
			:total="state.total"
			:layout="pageLayout"
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
			background
		>
		</el-pagination>
		<el-dialog v-model="dialogVisible">
			<img v-if="dialogImageType == 1" w-full style="max-width: 100%;" :src="dialogImageUrl" />
			<div v-if="dialogImageType == 2">
				<img v-for="item,i in dialogImageUrls" :key="i" w-full style="max-width: 100%;margin:8px;" :src="item" />
			</div>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, nextTick, onActivated } from 'vue'
import { useCrud } from '@/hooks'
import { IHooksOptions } from '@/hooks/interface'
import { hasRule, isJSONTest } from '@/utils/tool'

const props = defineProps({
	// 分页配置
	pageLayout: {
		type: String,
		default:'total, prev, pager, next'
	},
	// 表格高度
	tableHeight: {
		type: Number,
		default: 500
	},
	// 表格数据
	tableData: {
		type: Array,
		default: []
	},
	// 表头数据
	tableProp: {
		type: Array,
		default: []
	},
	// 筛选字段
	queryForm: {
		type: Object,
		default: {}
	},
	// 数据接口
	dataListUrl: {
		type: String,
		default:''
	},
	// 操作数组
	option: {
		type: Array,
		default: []
	},
	// 操作区宽度
	optionWidth: {
		type: String,
		default: '120'
	},
	// 特殊处理方式：1、数据登记合并显示
	specialType: {
		type: Number,
		default: 0
	},
	// 是否带分页
	isPage: {
		type: Boolean,
		default: true
	},
	// 是否显示分页组件
	showPage: {
		type: Boolean,
		default: true
	},
	// 否在创建页面时，调用数据列表接口
	createdIsNeed: {
		type: Boolean,
		default: true
	},
	// 自定义接口数据格式
	diyDataProp: {
		type: String,
		default:''
	},
	setSizeFixed: {
		type: Number,
		default: 20
	},
})
const emit = defineEmits(['change','handleOption','handleSwitch'])
const setDataList = computed(() => {
	if(props.specialType == 1){
		state.dataList?.forEach((item: any) => {
			let recordDetail: any = []
			for(let key in item){
				if(key.indexOf('custom_column') != -1 && item[key] && isJSONTest(item[key])){
					recordDetail.push(JSON.parse(item[key]))
				}
			}
			item.recordDetail = recordDetail
		})
	}
	return state.dataList
})
const dialogVisible = ref(false)
const dialogImageType = ref(1) // 1单图，2多图
const dialogImageUrl = ref('')
const dialogImageUrls = ref([])
// 编辑器change事件触发
// 设置表格数据内容：例：1是0否
const setRadioData = (list: any,val: any) => {
	return list?.find((i:any)=>i.value==val)?.label || ''
}
// 图片预览（单图）
const preimg = (e: any) => {
	dialogImageType.value = 1
	dialogImageUrl.value = e
	dialogVisible.value = true
}
// 图片预览(多图)
const preimgs = (e: any) => {
	dialogImageType.value = 2
	dialogImageUrls.value = e.split(',')
	dialogVisible.value = true
}
// 获取对象属性值 多级属性'a.b' = obj.a.b
const getPropertyByPath = (object: any, propertyPath: any) => {
    let properties = propertyPath.split(".");
    let value = object;
    for (let property of properties) {
        if (value) {
            value = value[property];
        }
    }
    return value;
}
// 操作内容
const handleClick = (row: any, val: any) => {
	emit('handleOption',{row:row,val:val})
}
// 滑块操作
const handleSwitch = (id: any,e: any) => {
	emit('handleSwitch',{id:id,e:e})
}

const setCustomColumn = (val: any,value: any) => {
	let objs = val?JSON.parse(val):{}
	return objs[value] || ''
}
const state: IHooksOptions = reactive({
	diyDataProp:props.diyDataProp,
	createdIsNeed:false,
	dataListUrl: props.dataListUrl,
	isPage: props.isPage,
	setSize:props.setSizeFixed
})
const { getDataList, selectionChangeHandle, sizeChangeHandle, currentChangeHandle, deleteHandle, resetSearch } = useCrud(state)

const setList = (list: any) => {
	state.dataList = list
}

onMounted(() => {
	if(props.createdIsNeed){
		if(Object.values(props.queryForm)?.length){
			state.queryForm = props.queryForm
		}
		getDataList()
	}
})
defineExpose({
	getDataList,
	setList
})
</script>
<style lang="scss" scoped>
.table-custom {
	width: 100%;
}
</style>
